package com.fat.service.impl;

import com.fat.contains.ContainsStatus;
import com.fat.mapper.CategoryMapper;
import com.fat.pojo.Category;
import com.fat.pojo.Result;
import com.fat.service.CategoryService;
import com.fat.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Result addCategory(Category category) {
        //获取用户信息
        Map<String, Object> map = ThreadLocalUtil.get();
        int id = (int) map.get("id");
        category.setCreateUser(id);
        //判断当前文章分类名称是否已添加
        if (categoryMapper.findByName(category.getCategoryName(),id) > 0) {
            return Result.error(ContainsStatus.CATEGORY_NAME_EXIST);
        }
        //插入数据
        int result = categoryMapper.insert(category);
        return result > 0 ? Result.success() : Result.error(ContainsStatus.CATEGORY_ADD_ERROR);
    }

    @Override
    public Result listCategory() {
        //获取当前登录的用户信息
        Map<String, Object> map = ThreadLocalUtil.get();
        int id = (int) map.get("id");
        //查询当前用户创建的文章分类
        List<Category> list = categoryMapper.findByCreateUser(id);
        return Result.success(list);
    }

    @Override
    public Result getCategoryDetail(int id) {
        return Result.success(categoryMapper.findById(id));
    }

    @Override
    public Result updateCategory(Category category) {
        int result = categoryMapper.update(category);
        return result > 0 ? Result.success() : Result.error(ContainsStatus.CATEGORY_UPDATE_ERROR);
    }

    @Override
    public Result deleteCategory(int id) {
        int result = categoryMapper.delete(id);
        return result > 0 ? Result.success() : Result.error(ContainsStatus.CATEGORY_DELETE_ERROR);
    }
}
